package io.gitee.zhucan123.core.infrastructure;

import lombok.extern.java.Log;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ActiveProfilesResolver;
import org.springframework.test.util.MetaAnnotationUtils;
import org.springframework.util.StringUtils;

import java.util.LinkedHashSet;
import java.util.Set;

/**
 * 用于支持运行时动态的 ActiveProfiles 注解
 * 将环境变量中的 MAVEN_TEST_PROFILE 指定的值加入到（执行mvn test时）的active profiles中
 * 使用方法：在单元测试类上加上注解 @ActiveProfiles(value = "local", resolver = MvnTestProfileResolver.class)
 * 注解上原有的 local 仍然会被保留
 */
@Log
public class MvnTestProfileResolver implements ActiveProfilesResolver {

  @Override
  public String[] resolve(Class<?> testClass) {

    final Set<String> activeProfiles = new LinkedHashSet<>();

    // 将注解中定义的activeProfiles加入到返回列表中
    Class<ActiveProfiles> annotationType = ActiveProfiles.class;
    MetaAnnotationUtils.AnnotationDescriptor<ActiveProfiles> descriptor = MetaAnnotationUtils.findAnnotationDescriptor(testClass, annotationType);

    if (descriptor == null) {
//			if (logger.isDebugEnabled()) {
//				logger.debug(String.format(
//					"Could not find an 'annotation declaring class' for annotation type [%s] and class [%s]",
//					annotationType.getName(), testClass.getName()));
//			}
    } else {
      Class<?> declaringClass = descriptor.getDeclaringClass();
      ActiveProfiles annotation = descriptor.synthesizeAnnotation();

//			if (logger.isTraceEnabled()) {
//				logger.trace(String.format("Retrieved @ActiveProfiles [%s] for declaring class [%s].", annotation,
//					declaringClass.getName()));
//			}

      for (String profile : annotation.profiles()) {
        if (StringUtils.hasText(profile)) {
          activeProfiles.add(profile.trim());
        }
      }
    }

    // 能过环境变量 是否存在，判断是否是 mvn test
    String value = System.getenv("MAVEN_TEST");
    if(value != null && value.length() > 0) {
      activeProfiles.add(value);
    }
    return StringUtils.toStringArray(activeProfiles);
  }

}
